<?php
header('Content-Type:tex/html;charset=utf-8');
$link=mysqli_connect('localhost','root','','itcast');
//mysql_connet();老的
//判断数据库连接是否成功，如果不成功则显示错误信息并终止脚本继续执行
if(!$link){
    die('连接数据库失败！'.mysqli_error($link));
}
//设置字符集，选择数据库
mysqli_query($link,'set names utf8');
mysqli_query($link,'use `itcast`');
$error=array();//保存错误信息
if(!empty($_POST)){
    $username=isset($_POST['username'])?trim($_POST['username']):'';
    $password=isset($_POST['password'])?$_POST['password']:'';
    require 'check_form.lib.php';
    if(($result=checkUsername($username))!=true) $error[]=$result;
    if(($result=checkPassword($password))!=true) $error[]=$result;
    if(empty($error)){
        $username=mysqli_real_escape_string($link,$username);
        $sql="select `id`,`password`from`user` where `username`='$username'";
        if($rst=mysqli_query($link,$sql)){
            $row=mysqli_fetch_assoc($rst);
            $password_db=md5($row['salt'].md5($password));
            if($password_db==$row['password']){
                if(isset($_POST['auto_login']) && $_POST['auto_login']=='on'){
                    $ua=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
                    $password_cookie=md5($row['password'].md5($ua.$row['salt']));
                    $cookie_expire=time()+2592000;
                    setcookie('username',$username,$cookie_expire);
                    setcookie('password',$password_cookie,$cookie_expire);
                }
                session_start();
                $_SESSION['userinfo']=array(
                    'id'=>$row['id'],
                    'username'=>$username
                );
                header('Location:user.php');
                die;
            }
        }
        $error[]='用户名不存在或密码错误。';
    }
}
if(isset($_COOKIE['username']) && isset($_COOKIE['password'])){
    $username=$_COOKIE['username'];
    $password=$_COOKIE['password'];
    $username=mysqli_real_escape_string($link,$username);
    $sql="select `id`,`password`,`slat` from`user` where `username`='$username'";
    if($rst=mysqli_query($link,$sql)){
        $row=mysqli_fetch_assoc($rst);
        $ua=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $password_cookie=md5($row['password'].md5($ua.$row['salt']));
        if($password==$password_cookie){
            session_start();
            $_SESSION['userinfo']=array(
                'id'=>$row['id'],
                'username'=>$username
            );
            header('Location:user.php');
            die;
        }
    }
    $error[]='登录状态已失效，请重新登陆。';
}
define('APP','itcast');
require 'login_html.php';
